#!/bin/bash
# Build docker image
# Copyright (c) MarsBighead, 2024. All rights reserved.
#
#openGauss is licensed under Mulan PSL v2.
#You can use this software according to the terms and conditions of the Mulan PSL v2.
#You may obtain a copy of Mulan PSL v2 at:
#
#          http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
#-------------------------------------------------------------------------
#
# entrypint.sh
#    Build docker image
#
# IDENTIFICATION
#    phant-container/images/entrypint.sh
#
#-------------------------------------------------------------------------

# set -eu
set -Eeo pipefail
# GAUSSHOME is the home path of which openGuass binary is installed, and it should be a fixed directory in an image
# GAUSSHOME has been decleared in Dockerfile
# declare GAUSSHOME=${GAUSSHOME:-/opt/openGauss}

declare GAUSSDATA=${GAUSSDATA:-/opt/data}
# Suport recovery from env variables
declare GS_PORT=${GS_PORT:-5432}
# GS_USER is initial user 
declare GS_USER=${GS_USER:-omm}

# declare GS_REPLUSER=${GS_REPLUSER:-sufe}
# GS_USERNAME is sysadmin user with remote access,
#             and it can be empty if no remote access requirements 
# declare GS_USERNAME=${GS_USERNAME:-hbu}
declare PWFILE=$GAUSSDATA/.pwfile
# cluster_state is used for cluster state management.
declare cluster_state=""


hostname=$(hostname)
current_dir=$(cd $(dirname $0); pwd)
cd ${current_dir}

source /opt/lib.sh

# check to see if this file is being run or sourced from another script
function _is_sourced() {
    [ "${#FUNCNAME[@]}" -ge 2 ] \
       && [ "${FUNCNAME[0]}" = '_is_sourced' ] \
       && [ "${FUNCNAME[1]}" = 'source' ]
}

# xlog output log message with timestamp
function xlog(){
    message=$@
    filename=$(basename $0)
    echo "$(date "+%Y-%m-%d %T") [$USER] [$filename] $message"
}

function _opengauss_want_help() {
    local arg
    count=1
    for arg; do
        case "$arg" in
        # postgres --help | grep 'then exit'
        # leaving out -C on purpose since it always fails and is unhelpful:
        # postgres: could not access the server configuration file "/var/lib/postgresql/data/postgresql.conf": No such file or directory
            -'?'|--help|--describe-config|-V|--version)
                return 0
                ;;
            esac
        if [ "$arg" == "-M" ]; then
            SERVER_MODE=${@:$count+1:1}
            echo "openGauss DB SERVER_MODE = $SERVER_MODE"
            shift
        fi
        count=$[$count + 1]
    done
    return 1
}

#############################################
## Check openGauss instance and CM Cluster ##
#############################################
function generate_node_conf(){
    xlog  "Generate openGauss cluster XML configure cluster.xml"
    generate_conf
    #generate_xml
    xlog  "Generate openGauss cluster static configure cluster_static_config"
    generate_static_config_file
    get_nodeid
    if [[ $nodeid -eq -1 ]];then
        xlog  "Get node id failed at host ${HOSTNAME}, error: nodeid=$nodeid"
        exit 1
    fi
    xlog  "Get node id successfully at host ${HOSTNAME}, nodeid=$nodeid"
    echo "to-do: check if cms, opengauss or cms&opengauss"
    set_authorized_keys
    get_componets
    if [[ -z $components ]];then
        xlog  "Get components failed with invalid value: ${components}"
        exit 1
    fi
    xlog  "Get components successfully with valid value: ${components}"
}

function init_cm_server(){ 
    if [ $components == "cms" ] || [ $components == "cms-dn" ];then
        init_cm_config
        generate_cm_cert
    else 
        init_cma_config
        generate_cma_cert
    fi
}


function init_datanode(){
    if [[ $components == "cms" ]];then
        xlog "Skip initialize openGauss cluster"
        return
    fi
    xlog "Start to initialize openGauss cluster"
    docker_init_database
    echo
    xlog "Setup openGauss instance configure with redirect(>>)"
    opengauss_setup_postgresql_conf
    opengauss_setup_hba_conf
    if [ $GAUSS_EDITION != "lite" ];then
        opengauss_setup_mot_conf
    fi
    echo
    xlog  "Setup openGauss cluster configure"
    setup_opengauss_cluster_conf
    echo
    xlog  "Initialize openGauss datanode successfully"
    return 
}


function generate_restart_conf(){
    if [ -f "${GAUSSDATA}/cluster.xml" ]; then
        xlog  "Exist openGauss cluster configure cluster.xml "
    else
        xlog  "Re-generate openGauss cluster configure cluster.xml"
        #generate_conf
        generate_xml
    fi
    if [ !-f ${CM_HOME}/bin/cluster_static_config ]; then
        xlog  "Exist openGauss cluster static config cluster.xml "
        generate_static_config_file
    fi
}

function main() {
    echo "####"
    echo "Step.1 Initialize ENV variables for openGuass cluster"
    echo "####"
    set_envfile 
    ## docker_setup_env set value to DATABASE_ALREADY_EXISTS
    docker_setup_env
    # when? how? check env hosts
    # check_env_hosts
    xlog "Initialize socket tmp directory(\$PGHOST) ${PGHOST}"    
    docker_init_socket_tmp
    echo
    echo "####"
    echo "Step.2 Generate node configure at host $HOSTNAME"
    echo "####"
    generate_node_conf
    echo
    echo "####"
    echo "Step.3 Initialize CM component"
    echo "####"
    init_cm_server
    # only run initialization on an empty data directory
    if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
        echo "####"
        echo "Step.4 Initialize openGauss datanode if required"
        echo "####"
        echo
        init_datanode
        echo "####"
        echo "Step.5 Luanch openGauss components with om_monitor"
        echo "####"
        echo
        xlog  "Launch om_monitor process..."
        echo
        echo "om_monitor -L $GAUSSLOG/cm/om_monitor"
        # to-do: change to use exec launch om_monitor process
        # exec om_monitor -L $GAUSSLOG/cm/om_monitor
        om_monitor -L $GAUSSLOG/cm/om_monitor
    else
        ## to-do: add initialize single node bussiness logic
        echo "####"
        echo "Step.4 Check restart configure for openGauss cluster"
        echo "####"
        echo
        generate_restart_conf
        echo
        echo "####"
        echo "Step.5 Luanch openGauss components with om_monitor"
        echo "####"
        echo
        xlog "Restart openGauss instance in the cluster"
        echo
        cd $GAUSSDATA
        # to-do: change to use exec launch om_monitor process
        # exec om_monitor -L $GAUSSLOG/cm/om_monitor
        om_monitor -L $GAUSSLOG/cm/om_monitor
    fi

}

if ! _is_sourced; then
    main "$@"
fi